import {Base64} from "js-base64";

// 文本
let instance ={
    isEmpty:(value) =>{
        return !!!value;
    },
    isNotEmpty:(value) =>{
        return !!value;
    },
};


instance.string = {
    startsWith: (str,search)=>{
        return str.startsWith(search);
    },
    endsWith: (str,search)=>{
        return str.endsWith(search);
    },
    replaceFirst: (str,search,target)=>{
        return str.replace(search,target);
    },
    replaceAll: (str,search,target)=>{
        //RegExp(",", "g")的第一个参数代表要替换的字符，第二个代表修饰符，g代表匹配全部，t代表只匹配一次
        return str.replace(RegExp(search, "g"),target);
    },
    encodeBase64 : (str)=>{
        return Base64.encode(str);
    },
    decodeBase64 : (encoded) =>{
        return Base64.decode(encoded);
    },
}

// http url
instance.http={
    currentUrl:()=>{
        return window.location.href;
    },

    protocol: (uri)=>{
        let parser = instance.http.parse(uri);
        return parser.protocol;
    },

    host: (uri)=>{
        let parser = instance.http.parse(uri);
        return parser.host;
    },

    hostname: (uri)=>{
        let parser = instance.http.parse(uri);
        return parser.hostname;
    },

    port: (uri)=>{
        let parser = instance.http.parse(uri);
        return parser.port;
    },

    pathname: (uri)=>{
        let parser = instance.http.parse(uri);
        return parser.pathname;
    },

    parameter: (uri,name)=>{
        let url = uri.split("?")[1];
        const urlSearchParams = new URLSearchParams(url);
        const params = Object.fromEntries(urlSearchParams.entries());
        return params[name];
    },

    parse:(location) =>{
        //const urlString = 'http://www.example.com:8000/path/name?query=string#hash';
        return new URL(location);
        // console.log(url.protocol); // 输出 'http:'
        // console.log(url.hostname); // 输出 'www.example.com'
        // console.log(url.port);     // 输出 '8000'
        // console.log(url.host);     // 输出 'www.example.com:8000'
        // console.log(url.href);     // 输出完整的URL字符串
        // console.log(url.pathname); // 输出 '/path/name'
        // console.log(url.search);   // 输出 '?query=string'
        // console.log(url.hash);     // 输出 '#hash'
    },
}

// 数组
instance.array={
    isArray: (arr) =>{
        return !!arr && Array.isArray(arr);
    },
    isEmpty: (arr) =>{
        return instance.array.isArray(arr) && arr.length ===0;
    },
    isNotEmpty: (arr) =>{
        return instance.array.isArray(arr) && arr.length !==0;
    },
    find: (arr,fieldName,fieldValue) =>{
        if(this.isArray(arr)){
            return arr.filter(x => x[fieldName] === fieldValue);
        }
        return null;
    },
    remove: (arr,fieldName,fieldValue) =>{
        if(this.isArray(arr)){
            arr = arr.filter(x => x[fieldName] !== fieldValue);
            return arr;
        }
        return arr;
    },
}

// 日期
instance.date={

}

const JsHelper = instance
export { JsHelper }

